<?php
/**
 * @title 120. 三角形最小路径和 - 递归
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[][] $triangle
     * @return Integer
     */
    function minimumTotal($triangle) {
        /**
         * @since 2020-07-14 极端情况排除
         */
        $len = count($triangle);
        if($len<1){
            return false;
        } else {}

        /**
         * @since 2020-07-14 2层循环
         */
        for ($i=1; $i<$len; $i++){
            $l = count($triangle[$i]);

            /**
             * @since 2020-07-14 头尾排除, 避免isset判断
             */
            $triangle[$i][0] += $triangle[$i-1][0];
            $triangle[$i][$l-1] += $triangle[$i-1][$l-2];

            /**
             * @since 2020-07-14 最小路径
             */
            for($j=1; $j<=$l-2; $j++){
                $triangle[$i][$j] += min($triangle[$i-1][$j-1], $triangle[$i-1][$j]);
            }
        }

        /**
         * @return
         */
        return min($triangle[$len-1]);
    }
}





/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.14.php
 */
$datas = [
    [
        [2],
        [3,4],
        [6,5,7],
        [4,1,8,3],
    ],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->minimumTotal($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
